#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
构建可执行文件的脚本
"""

import os
import sys
import subprocess
from pathlib import Path

def build_exe():
    """构建exe文件"""
    
    # 项目根目录
    project_root = Path(__file__).parent
    
    # 图标文件路径
    icon_path = project_root / "ico.png"
    
    # 检查图标文件是否存在
    if not icon_path.exists():
        print(f"警告: 图标文件 {icon_path} 不存在，将使用默认图标")
        icon_arg = ""
    else:
        icon_arg = f"--icon={icon_path}"
    
    # PyInstaller命令
    cmd = [
        "pyinstaller",
        "--onefile",  # 打包成单个exe文件
        "--windowed",  # 无控制台窗口
        "--name=Gitee仓库批量管理工具",  # 可执行文件名称
        icon_arg,
        "--add-data=config.json;.",  # 包含配置文件
        "--add-data=demo_config.json;.",  # 包含演示配置
        "--hidden-import=tkinter",
        "--hidden-import=ttkbootstrap",
        "--hidden-import=requests",
        "--hidden-import=git",
        "--hidden-import=PIL",
        "--hidden-import=markdown",
        "--hidden-import=webbrowser",
        "--hidden-import=tempfile",
        "--hidden-import=threading",
        "--hidden-import=json",
        "--hidden-import=os",
        "--hidden-import=sys",
        "--hidden-import=datetime",
        "--hidden-import=pathlib",
        "--hidden-import=typing",
        "--hidden-import=logging",
        "--hidden-import=re",
        "--hidden-import=base64",
        "--hidden-import=urllib",
        "--hidden-import=urllib.parse",
        "--hidden-import=urllib.request",
        "--hidden-import=urllib.error",
        "--hidden-import=http",
        "--hidden-import=http.client",
        "--hidden-import=email",
        "--hidden-import=email.mime",
        "--hidden-import=email.mime.text",
        "--hidden-import=email.mime.multipart",
        "--clean",  # 清理临时文件
        "main.py"  # 主程序文件
    ]
    
    # 过滤空参数
    cmd = [arg for arg in cmd if arg]
    
    print("开始构建可执行文件...")
    print(f"命令: {' '.join(cmd)}")
    
    try:
        # 执行PyInstaller
        result = subprocess.run(cmd, cwd=project_root, check=True, capture_output=True, text=True)
        print("构建成功！")
        print("输出:", result.stdout)
        
        # 检查生成的文件
        exe_path = project_root / "dist" / "Gitee仓库批量管理工具.exe"
        if exe_path.exists():
            print(f"可执行文件已生成: {exe_path}")
            print(f"文件大小: {exe_path.stat().st_size / 1024 / 1024:.2f} MB")
        else:
            print("错误: 可执行文件未生成")
            
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False
    except FileNotFoundError:
        print("错误: 未找到PyInstaller，请先安装: pip install pyinstaller")
        return False
    
    return True

if __name__ == "__main__":
    success = build_exe()
    if success:
        print("\n✅ 构建完成！可执行文件位于 dist/ 目录中")
    else:
        print("\n❌ 构建失败！")
        sys.exit(1)
